package com.itheima.duofa;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Objects;

/**
 * 目标：创建一个服务器，接收客户端发送的数据并打印在控制台。
 */
public class Server {

    public static void main(String[] args) throws Exception {
        //1.创建ServerSocket对象，注册服务器端端口
        ServerSocket ss = new ServerSocket(10086);

        //2.使用ServerSocket对象的accept方法获取服务器端Socket对象
        System.out.println("服务器已启动，等待客户端连接...");
        Socket serverScoket = ss.accept(); //阻塞，一直等待客户端连接

        //2.获取Socket的输入流对象
        InputStream os = serverScoket.getInputStream();
        BufferedReader  br = new BufferedReader( new InputStreamReader(os) );

        //3.读取客户端数据
        while (true) {
            String msg = null;
            try {
                msg = br.readLine();
            } catch (IOException e) {
                System.out.println("客户端强制退出！");
                //throw new RuntimeException(e);
                break;
            }
            System.out.println("接收到客户端的消息：" + msg);
            if (Objects.equals(msg, "886")){
                System.out.println("客户端已退出！");
                break;
            }
        }

        //4.资源释放
        br.close(); //关闭输入流
        serverScoket.close(); //关闭Socket
    }
}
